#pragma once

#include <string>
#include "Protocol.hpp"

enum {
    DivErr = 1,
    ModErr,
    Unknown
};

class ServerCal
{
public:
    //接收一个request对象，返回一个response对象
    Response CalculatorHelper(const Request& request)
    {
        Response rs;
        switch (request._op)
        {
        case '+':
            rs._result = request._x + request._y;
            rs._code = 0;
            break;
        case '-':
            rs._result = request._x - request._y;
            rs._code = 0;
            break;
        case '*':
            rs._result = request._x * request._y;
            rs._code = 0;
            break;
        case '/':
            {
                if(request._y == 0) { rs._code = DivErr; }
                else {
                    rs._result = request._x / request._y;
                    rs._code = 0;
                }
            }
            break;
        case '%':
            {
                if(request._y == 0) { rs._code = ModErr; }
                else {
                    rs._result = request._x % request._y;
                    rs._code = 0;
                }
            }
            break;
        default:
            rs._code = Unknown;
            break;
        }
        return rs;
    }
    //接收一个request package，返回一个response package
    std::string Calculator(const std::string& package)
    {
        std::string msg;
        Decode(package, &msg);
        Request rq;
        rq.Deserialization(msg);
        Response rs = CalculatorHelper(rq);
        std::string res_msg = rs.Serialization();
        std::string res_package;
        Encode(res_msg, &res_package);
        return res_package;
    }
};